package com.ipet.app.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import com.afollestad.materialdialogs.MaterialDialog;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.gson.Gson;
import com.ipet.app.R;
import com.ipet.app.api.BaseCallBack;
import com.ipet.app.api.RequestManager;
import com.ipet.app.bean.apiResponseBean.BaseResponse;
import com.ipet.app.common.AppConfig;
import com.ipet.app.ui.common.MultiTagViewSelectorActivity;
import com.ipet.app.ui.base.SwipeBackActivity;
import com.ipet.app.util.ImageFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by jindongping on 16/3/14.
 */
public class SendPostActivity extends SwipeBackActivity {
    //多图选择回调标志
    private static final int REQUEST_IMAGE = 2;
    //多图选择回调结果
    private ArrayList<String> mSelectPath;
    //标签选择回调标志
    private static final int REQUEST_TAG = 3;
    //标签选择回调结果
    private ArrayList<Integer> mSelectTagsId;
    //该activity全局容器
    private CoordinatorLayout coordinatorLayout;
    private FloatingActionMenu fabMenu;
    private FloatingActionButton fab1, fab2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_post);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);
        initToolbar();
        initFloatingActionMenu();
    }

    private void initFloatingActionMenu() {
        fabMenu = (FloatingActionMenu) findViewById(R.id.fab_menu);
        fab1 = (FloatingActionButton) findViewById(R.id.fab1);
        fab2 = (FloatingActionButton) findViewById(R.id.fab2);
        fab1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fabMenu.toggle(true);
                goToMultiImageSelector();
            }
        });
        fab2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fabMenu.toggle(true);
                goToTagViewSelector();
            }
        });
    }

    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("发帖");
        toolbar.setNavigationIcon(R.drawable.btn_back);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.send_post_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_send_post) {
            String title = ((EditText) findViewById(R.id.et_title)).getText().toString().trim();
            String content = ((EditText) findViewById(R.id.et_content)).getText().toString().trim();
            if (content.length() < 1) {
                snackShow(coordinatorLayout, "请编辑内容");
            } else {
                final RequestBody titleRequest = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), title);
                final RequestBody contentRequest = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), content);
                String topics = "";
                if (mSelectTagsId != null) {
                    topics = new Gson().toJson(mSelectTagsId.toArray());
                }
                final RequestBody topicRequest = RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"), topics);
                final MaterialDialog dialog = showLoadingDialogNoTitle("发贴中...");
                RatioCallBack callBack = new RatioCallBack() {
                    @Override
                    public void callBack(RequestBody[] imageRequests) {
                        RequestManager.getApi().writePost(titleRequest, contentRequest, topicRequest, imageRequests).enqueue(new BaseCallBack<BaseResponse>(coordinatorLayout, dialog) {
                            @Override
                            public void onRequestSuccess(BaseResponse response) {
                                finish();
                            }
                        });
                    }
                };
                new RatioThread(mSelectPath, callBack).start();

            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    interface RatioCallBack {
        void callBack(RequestBody[] imageRequests);
    }

    /**
     * 压缩图片后 将图片封装成 RequestBody 通过RatioCallBack回调出来
     */
    class RatioThread extends Thread {
        private List<String> needRatioPath;
        RatioCallBack callBack;

        public RatioThread(List<String> needRatioPath, RatioCallBack callBack) {
            this.needRatioPath = needRatioPath;
            this.callBack = callBack;
        }

        @Override
        public void run() {
            super.run();
            if (needRatioPath == null) {
                callBack.callBack(null);
                return;
            }
            RequestBody[] imageRequests = new RequestBody[needRatioPath.size()];
            for (int i = 0; i < needRatioPath.size(); i++) {
                Bitmap bitmap = ImageFactory.ratio(needRatioPath.get(i), 480f, 880f);
                String compressFilePath = ImageFactory.storeImage(bitmap, AppConfig.getInstance().getUpLodeCache() + File.separator + System.currentTimeMillis() + ".jpeg");
                //压缩失败
                if (compressFilePath == null) {
                    callBack.callBack(null);
                    return;
                }
                imageRequests[i] = RequestBody.create(MediaType.parse("image/jpeg"), new File(compressFilePath));
            }
            callBack.callBack(imageRequests);
        }
    }


    private void goToMultiImageSelector() {
        Intent intent = new Intent(getApplicationContext(), MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);

        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);

        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

        startActivityForResult(intent, REQUEST_IMAGE);
    }

    private void goToTagViewSelector() {
        Intent intent = new Intent(getApplicationContext(), MultiTagViewSelectorActivity.class);
        startActivityForResult(intent, REQUEST_TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                fab1.setLabelText("已选" + mSelectPath.size() + "张图片,点击重新选择");
            }
        }
        if (requestCode == REQUEST_TAG) {
            if (resultCode == RESULT_OK) {
                mSelectTagsId = data.getIntegerArrayListExtra(MultiTagViewSelectorActivity.EXTRA_RESULT);
                fab2.setLabelText("已选" + mSelectTagsId.size() + "个标签,点击重新选择");
            }
        }
    }
}
